package com.minazuki.signinserver.web;

import com.minazuki.signinserver.config.JwtProperties;
import com.minazuki.signinserver.pojo.api.UserInfo;
import com.minazuki.signinserver.pojo.dao.User;
import com.minazuki.signinserver.pojo.msg.Msg;
import com.minazuki.signinserver.service.AuthService;
import com.minazuki.signinserver.service.UserService;
import com.minazuki.signinserver.utils.CookieUtils;
import com.minazuki.signinserver.utils.JsonUtils;
import com.minazuki.signinserver.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
@RequestMapping("user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    //    @Autowired
//    private AuthService authService;
    @Autowired
    private UserService userService;
    @Autowired
    AuthService authService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping(value = "register")
    @ResponseBody
    public ResponseEntity<Void> register(@Valid @RequestBody User user) {
        Boolean boo = this.userService.register(user);
        if (boo == null || !boo) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    /*
        @GetMapping("query")
        public ResponseEntity<User> queryUser(
                @RequestParam("username") String username,
                @RequestParam("password") String password
        ) {
            User user = this.userService.queryUser(username, password);
            if (user == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
            }
            return ResponseEntity.ok(user);
        }
    */
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(@Valid @RequestBody User user,
                                               HttpServletRequest request,
                                               HttpServletResponse response) {
//        logger.info("进入控制器");
        logger.info("login: " + JsonUtils.serialize(user));
        // 登录校验
        String token = authService.authentication(user.getUsername(), user.getPassword());
        if (StringUtils.isBlank(token)) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
        CookieUtils.setCookie(request, response, jwtProperties.getCookieName(),
                token, jwtProperties.getCookieMaxAge(), false);

        logger.info(user.getUsername() + "登录成功");
        return ResponseEntity.ok().build();
    }

    @PostMapping("login")
    public ResponseEntity<UserInfo> login(HttpServletResponse response, HttpServletRequest request) {
        User u = new User();
        u.setUsername(request.getParameter("username"));
        return ResponseEntity.ok().build();
    }

    @GetMapping("verify")
//    @PostMapping("verify")
    public ResponseEntity<Msg<UserInfo>> verify(@CookieValue("SIGNSYS_TOKEN") String token, HttpServletResponse response, HttpServletRequest request) {
        try {
            Msg msg = new Msg();
            UserInfo info = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            msg.setUserInfo(info);
            String newToken = JwtUtils.generateToken(info, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), newToken, jwtProperties.getCookieMaxAge());
            return ResponseEntity.ok(msg);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}